package cn.hughie.thread;

import java.util.concurrent.*;

/**
 * 缓存器
 *
 * @author yuh
 * @date 2018/5/24 13:30
 */
public class Memorizer {

    private ConcurrentHashMap<Integer, Future<Integer>> cache = new ConcurrentHashMap<>();
    private Calculator calculator = Calculator.getInstance();
    private static final ExecutorService pool = Executors.newFixedThreadPool(5);

    public Integer compute(int a) throws ExecutionException, InterruptedException {
        Future<Integer> vFuture = cache.get(a);
        if (vFuture == null) {
            Callable<Integer> callable = new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    System.out.println(Thread.currentThread().getName());
                    System.out.println("计算:" + a);
                    return calculator.compute(a);
                }
            };
            FutureTask<Integer> ft = new FutureTask<>(callable);
            Future<Integer> f = cache.putIfAbsent(a, ft);
            if (f == null) {
                //ft.run();
                pool.submit(ft);
                vFuture = ft;
            }
        } else {
            System.out.println("缓存命中:" + a);
        }
        return vFuture.get();
    }

}
